<#import "/spring.ftl" as spring/>
<script>
	var userId = 0;
	<#if userInfo?exists>userId = ${userInfo.id?default(0)}</#if>
	var roleIds = new Array();
	<#if userInfo?exists && userInfo.roleList?exists>
		<#list userInfo.roleList as role >
			roleIds.push(${role.id});
		</#list>
	</#if>
	function deleteUserRole(roleId){
		for(var i=0; i<roleIds.length; i++){
			if(roleIds[i] == roleId){
				roleIds.splice(i,1);
			}
		}
		$("#role_"+roleId).remove();
	}
	function addUserRole(roleId, roleName){
		var has = false;
		for(var i=0; i<roleIds.length; i++){
			if(roleIds[i] == roleId){
				has = true;
				break;
			}
		}
		if(has){
			alert("用户角色存在");
		}else{
			var label ='<label id="role_'+roleId+'">'+roleName+'<a href="javascript:deleteUserRole('+roleId+'})">删除</a></label>';
			$("#roleTd").append(label);
			roleIds.push(roleId);
		}
	}
	function saveUser(){
	
		var realname = $("#realname").val();
		var username = $("#username").val();
		if(!realname || !realname.trim()){
			alert("请输入真实姓名");
			return false;
		}
		if(!username || !username.trim()){
			alert("请输入账户");
			return false;
		}
		$.ajax({
			url:"/user/saveUser",
			dataType: "json",
			data:{
				userId: userId,
				roleIds: roleIds,
				realname: realname,
				username: username
			},
			traditional: true,  
			type:"POST",
			success:function(data){
				if(data.code != 200){
					alert(data.result);
				}else{
					alert("保存成功");
				}
			}
		});
	}
</script>
<div>
	<table>
		<tr>
			<td>真实姓名:</td><td><input type="text" id="realname" value="<#if userInfo?exists >${userInfo.realname}</#if>"></td>
			<td>账户:</td><td><input type="text" id="username" value="<#if userInfo?exists>${userInfo.username}</#if>"></td>
		</tr>
		<tr>
			<td>角色：</td>
			<td colspan=3 id="roleTd">
				<#if userInfo?exists && userInfo.roleList?exists>
					<#list userInfo.roleList as role >
						<label id="role_${role.id}">${role.roleName} <a href="javascript:deleteUserRole(${role.id})">删除</a></label>
					</#list>
				</#if>
			</td>
			<tr>
				<td>所有角色：</td>
				<td>
				<#list roleList as role>
						<label>${role.roleName}</label><a href="javascript:addUserRole(${role.id}, '${role.roleName}')">添加</a>
				</#list>
				</td>
			</tr>
			<tr>
				<td><a href="javascript:saveUser()">保存</a></td>
			</tr>
		</tr>
	</table>
		
</div>
